package android_rteditor.customsortricheditor.editor;

import android.animation.LayoutTransition;
import android.app.Activity;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import android_rteditor.customsortricheditor.R;
import android_rteditor.customsortricheditor.RichEditor;

/**
 * 统一的编辑器控制器
 * Created by chenxunlin01 on 2017/8/16.
 */

public class RichEditorController {

    private LinearLayout root;
    private Activity activity;
    private EditorItemFactory factory;
    private LayoutTransition mTransitioner;
    private EditorOnFocusChangeListener focusChangeListener;
    private EditorDomUtils editorDomUtils;
    // 当前光标所在的视图
    private IEditorItem curCursorView;

    public RichEditorController(RichEditor richEditor) {
        this.root = richEditor.getRoot();
        this.mTransitioner = root.getLayoutTransition();
        this.activity = (Activity) richEditor.getContext();
        factory = EditorItemFactory.newstance();
        editorDomUtils = new EditorDomUtils(this);
    }

    public void init() {
        // listener器初始化
        focusChangeListener = new EditorOnFocusChangeListener();
    }

    public Activity getActivity() {
        return activity;
    }

    public EditorDomUtils getEditorDomUtils() {
        return editorDomUtils;
    }

    public EditorOnFocusChangeListener getFocusChangeListener() {
        return focusChangeListener;
    }

    private IEditorItem getEditorItemByIndex(int index) {
        int count = root.getChildCount();
        if (count == 0 || index < 0 || index >= count) {
            return null;
        }
        return (IEditorItem) root.getChildAt(index);
    }

    /**
     * 获取光标所在项的索引
     *
     * @return
     */
    private int getCursorItemIndex() {
        if (curCursorView == null) {
            return 0;
        } else {
            return root.indexOfChild(curCursorView.getView());
        }
    }

    public int indexOfItem(IEditorItem item) {
        return root.indexOfChild((View) item);
    }

    public IEditorItem getChildAt(int index) {
        return (IEditorItem) root.getChildAt(index);
    }

    public void removeItem(IEditorItem item) {
        root.removeView((View) item);
    }

    /**
     * 获取编辑器的字体
     *
     * @return float
     */
    public float getEditTextSize() {
        return activity.getResources().getDimensionPixelOffset(R.dimen.common_edit_text_size);
    }

    /**
     * 获取编辑器的字体颜色
     *
     * @return
     */
    public int getEditTextColor() {
        return activity.getResources().getColor(R.color.common_edit_text_color);
    }

    /**
     * 获取编辑器的背景色
     *
     * @return
     */
    public int getEditTextBackgroundColor() {
        return activity.getResources().getColor(R.color.common_edit_text_background);
    }

    /**
     * 插入checkbox视图
     */
    public void insertCheckbox() {
        int curIndex = getCursorItemIndex();
        IEditorItem curItem = getEditorItemByIndex(curIndex);
        if (EditorItemFactory.EDITOR_ITEM_EDITTEXT == curItem.getType()) {
            RichEditText richEditText = (RichEditText) curItem.getView();
            CheckboxView checkboxView = editorDomUtils.createEditorCheckboxItem();
            editorDomUtils.textToCheckbox(richEditText, checkboxView);

        } else if (EditorItemFactory.EDITOR_ITEM_CHECKBOX == curItem.getType()) {
            CheckboxView checkboxView = (CheckboxView) curItem.getView();
            RichEditText richEditText = editorDomUtils.createEditorTextItem();
            editorDomUtils.checkboxToText(checkboxView, richEditText);
        } else {
            addEditorItem(editorDomUtils.createEditorCheckboxItem(), curIndex + 1);
        }
    }

    public void insertImage(String path) {
        // 判断要插入的图片前后是否有可输入的EditText，没有则需要在其前后添加EditText
        int curIndex = getCursorItemIndex();
        int imgIndex = curIndex + 1;
        if (!canEditor(curIndex)) {
            addEditorItem(editorDomUtils.createEditorTextItem(), -1);
            imgIndex++;
        }
        if (!canEditor(curIndex + 1)) {
            addEditorItem(editorDomUtils.createEditorTextItem(), curIndex + 1);
        }

        RichImage richImage = editorDomUtils.createEditorImageItem();
        richImage.loadImage(path);
        addEditorItem(richImage, imgIndex);
        // 控制光标
        IEditorItem nextItem = (IEditorItem) root.getChildAt(imgIndex + 1);
        if (nextItem instanceof RichEditText) {
            ((RichEditText) nextItem).focus(false);
        }else if(nextItem instanceof CheckboxView){
            ((CheckboxView) nextItem).focus(false);
        }
    }

    /**
     * 插入音频
     */
    public void insertAudio() {
        RichAudio richAudio = editorDomUtils.createEditorAudioItem();
        int curIndex = getCursorItemIndex();
        IEditorItem curItem = (IEditorItem) root.getChildAt(curIndex);
        if (curItem instanceof RichEditText && ((RichEditText) curItem).isEmptyText()) {
            editorDomUtils.replaceView(richAudio, curItem);
            RichEditText richEditText = editorDomUtils.createEditorTextItem();
            addEditorItem(richEditText, curIndex + 1);
            richEditText.focus(false);
            return;
        }

        addEditorItem(richAudio, curIndex + 1);
        RichEditText richEditText = editorDomUtils.createEditorTextItem();
        addEditorItem(richEditText, curIndex + 2);
        richEditText.focus(false);
    }

    private void focus(int index) {
        if (index == -1) {
            index = root.getChildCount() - 1;
            if (index == -1) {
                return;
            }
        }
        IEditorItem item = (IEditorItem) root.getChildAt(index);
        if (item.getType() == EditorItemFactory.EDITOR_ITEM_EDITTEXT) {
            item.getView().requestFocus();
        }
    }

    public void addEditorTextItem(int index) {
        IEditorItem item = factory.createEditorItem(this, EditorItemFactory.EDITOR_ITEM_EDITTEXT);
        addEditorItem(item, index);
    }

    public void addEditorItem(IEditorItem item, int index) {
        if (index >= root.getChildCount()) {
            index = -1;
        }

        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT);
        if (index == -1) {
            root.addView(item.getView(), lp);
        } else {
            root.addView(item.getView(), index, lp);
        }
    }

    /**
     * 判断该项是否可以修改
     *
     * @param index
     * @return
     */
    private boolean canEditor(int index) {
        if (index == -1) {
            return false;
        }
        IEditorItem item = (IEditorItem) root.getChildAt(index);
        if (item != null && (EditorItemFactory.EDITOR_ITEM_EDITTEXT == item.getType() || EditorItemFactory
                .EDITOR_ITEM_CHECKBOX ==
                item.getType())) {
            return true;
        }

        return false;
    }

    /**
     * 删除图片
     *
     * @param richImage image
     */
    public void removeRichImage(RichImage richImage) {
        if (richImage != null) {
            root.removeView(richImage);
        }
    }

    /**
     * 删除音频
     *
     * @param richAudio audio
     */
    public void removeRichAudio(RichAudio richAudio) {
        if (richAudio != null) {
            root.removeView(richAudio);
        }
    }

    /**
     * 设置EditText的属性
     *
     * @param editText      editText
     * @param textSize      textSize
     * @param colorRes      colorRes
     * @param backgroundRes backgroundRes
     */
    public void updateEditText(EditText editText, float textSize, int colorRes, int backgroundRes) {
        editText.setTextColor(colorRes);
        editText.setBackgroundColor(backgroundRes);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
    }

    // 刪除動畫
    public void removeLayoutTransition() {
        root.setLayoutTransition(null);
    }

    // 恢复动画
    public void recoveryLayoutTransition() {
        root.setLayoutTransition(mTransitioner);
    }

    class EditorOnFocusChangeListener implements OnEditorFocusChangeListener {

        @Override
        public void onFocusChange(IEditorItem item, boolean hasFocus) {
            if (hasFocus) {
                curCursorView = item;
            }
        }
    }

}
